package com.xinpu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinpu.entity.TUserTag;
import com.xinpu.service.ITUserTagService;
import com.xinpu.service.OwnService;
import com.xinpu.service.TagAdminService;
import com.xinpu.vo.ResponseMessage;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * TagController
 *
 * @author ayuan
 * @date 2021/4/15
 */
@RestController
@RequestMapping("/tag")
public class TagController {


    @Resource
    private ITUserTagService itUserTagService;

    @Resource
    private TagAdminService tagAdminService;

    /**
     * 标签列表
     *
     * @return
     */
    @GetMapping("/list")
    public ResponseMessage list(
            @RequestParam("page") Integer page,
            @RequestParam("size") Integer size
    ) {
        return ResponseMessage.ok(itUserTagService.page(new Page<>(page, size)));
    }

    /**
     * 创建或编辑标签
     *
     * @param map
     * @return
     */
    @PostMapping("/createOrEdit")
    public ResponseMessage createOrEdit(@RequestBody Map<String, String> map) {
        TUserTag tUserTag = new TUserTag();
        String id = map.get("id");
        String name = map.get("name");
        QueryWrapper<TUserTag> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        wrapper.eq("tenant_id", OwnService.getLoginer().getTenantId()).or().eq("tenant_id", "0");
        TUserTag tUserTag1 = itUserTagService.getOne(wrapper);
        if (StringUtils.isNotBlank(id)) {
            tUserTag.setId(Integer.parseInt(id));
            if (tUserTag1 != null) {
                if (!tUserTag1.getId().toString().equals(id)) {
                    return ResponseMessage.error("标签名称重复,请重新提交");
                }
            }
            tUserTag.setName(name);
            tUserTag.setSid(0);
            itUserTagService.saveOrUpdate(tUserTag);
            return ResponseMessage.ok();
        }
        if (tUserTag1 == null) {
            tUserTag.setName(name);
            tUserTag.setSid(0);
            itUserTagService.saveOrUpdate(tUserTag);
            return ResponseMessage.ok();
        }
        return ResponseMessage.error("标签名称重复,请重新创建");
    }

    /**
     * 删除标签
     *
     * @param map
     * @return
     */
    @PostMapping("/delete")
    public ResponseMessage delete(@RequestBody Map<String, String> map) {
        itUserTagService.removeById(map.get("id"));
        return ResponseMessage.ok();
    }
}
